package com.REPDPMSystem.Service.Handler;

import com.REPDPMSystem.Entity.Monitor;
import com.REPDPMSystem.Mapper.MonitorMapper;
import com.REPDPMSystem.Service.MonitorService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class MonitorHandler extends ServiceImpl<MonitorMapper, Monitor> implements MonitorService {
    @Override
    public void downLoad(HttpServletResponse response, String staff_id, long startTime, long endTime) throws IOException {
        QueryWrapper<Monitor> wrapper = new QueryWrapper<>();
        wrapper.between("date", startTime, endTime)
                .eq("staff_id",staff_id);
        List<Monitor> MList =baseMapper.selectList(wrapper);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;fileName=" +
                new String((staff_id+String.valueOf(startTime)+String.valueOf(endTime)+".zip").getBytes("gbk"), "iso8859-1"));

        ServletOutputStream os = response.getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);


        byte[] buf = new byte[1024 * 4];
        for (int i = 0; i < MList.size(); i++) {
            zos.putNextEntry(new ZipEntry(String.valueOf(MList.get(i).getDate())+".png"));
            FileInputStream fis = new FileInputStream(MList.get(i).getFilepath());
            //使用字节缓冲输入流
            BufferedInputStream bis = new BufferedInputStream(fis);
            int len;
            while ((len = bis.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            bis.close();
        }

        //zos.closeEntry();
        zos.close();
    }
}
